<?php
require_once("global_funcs.inc.php");

class login
{
    private $data = null;
    private $error = null;
    
    function __construct($post_data)
    {
        $this->data = $post_data;
    }
    
    function authenticate()
    {
        global $ADMIN_LIST;
        
        // connect to the database
        $db = connect_db();
        
        // initially set the result to false
        $result = false;
        
        // escape the username to prevent SQL injection attack
        $username = mysql_real_escape_string($this->data['uname']);
        $password = sha1($this->data['passwd']);
        
        $auth_query = "select * from users,usertype where users.usertype = usertype.usertype_id and uname='{$username}'";
        $auth_res = mysql_query($auth_query,$db);
        
        if(mysql_num_rows($auth_res) == 0)
        {
            $this->error = "No such user found";
            return false;
        }
        
        $auth_row = mysql_fetch_object($auth_res);
        
        if($auth_row->activated != 0)
        {
            return false;
        }
        
        // if passwords match        
        if($auth_row->passwd == $password)
        {
            // this is going to be stored in the cookie
            $secret_pass = sha1(strrev($username));
            
            // set the username and the secret key in the cookie
            setcookie("uname",$username);
            setcookie("check",$secret_pass);
            setcookie("usertype",$auth_row->usertype_id);
            
            // set whether the logged-in user has admin rights or not
            if(in_array($auth_row->usertype_id,$ADMIN_LIST))
            {
                setcookie("admin_allowed",true);
            }
            else
            {
                setcookie("admin_allowed",false);
            }
            // set the logged-in value to true
            $result = true;
        }
        else
        {
            $this->error = "The supplied password is not correct";
        }
        // return the result
        return $result;
    }
    
    function getError()
    {
        return $this->error;
    }
}
?>
